<?php
namespace app\Http\Controllers\admin_system;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Redirect, Validator,Cookie,Response;
use App\Module\EntManageuser;
use \app\Module;
use Session;

class LoginController extends Controller
{

    /**
     * 后台登录界面
     *
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function login_get()
    {
        $data['title'] = '后台管理员登陆';
        $data['keywords'] = '后台管理员登陆 ';
        $data['description'] = '后台管理员登陆';

        //检查用户是否登录
        $AName  = Session::get('AName');
        $AKey   = Session::get('AKey');
        $manager= EntManageuser::where('UserName',$AName)->where("UserPwd",md5($AKey))->first();
        if($manager){
            return redirect('admin_system/index');
        }else{
            return view("admin_system/login/login" , $data);
        }
    }


    public function loginout(Request $request)
    {
        $request->session()->forget('AName');
        $request->session()->forget('AKey');
        $request->session()->forget('manageUser');
        $request->session()->forget('userId');
        Cookie::queue('AName', null , -1);
        Cookie::queue('AKey', null , -1);
        return redirect('/admin_system');
    }


    public function login_post(Request $request)
    {
        $rules = [
            'txtUserName' => 'required',
            'txtPassWord' => 'required'
        ];
        $messages = [
            'txtUserName.required' => '请输入用户名',
            'txtPassWord.required' => '请输入密码'
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator);
        }
        $UserName = EntManageuser::where('UserName', '=', $request->input('txtUserName'))->first();
        if (! $UserName) {
            return redirect::back()->withInput()->withErrors('您输入的用户名不存在！');
        }
        if ($UserName->UserPwd != md5($request->input('txtPassWord'))) {
            return redirect::back()->withInput()->withErrors('您输入的密码不正确！');
        }

        Session::put('AName',$request->input('txtUserName'), 60 * 24);
        Session::put('AKey',$request->input('txtPassWord'), 60 * 24);
        Session::put('userId',$UserName->UserID);
        Session::put('manageUser',$UserName);
        return redirect('admin_system/index');
    }
}